'use strict';

module.exports = {
  validate(rules, data) {
    const toValidate = (rules, data) => {

      // TODO 处理Array复杂类型的validate
      let errors = this.app.validator.validate(rules, data);
      if (!errors) {
        Object.keys(data)
          .some(field => {
            return rules[field] && rules[field].validators && rules[field].validators.some(item => {
              if (item.type === 'required') {
                return true;
              }
              if (!item.validator(data[field])) {
                errors = item.message;
                return true;
              }
              return false;
            });
          });
      }
      if (errors) {
        this.throw(422, 'Validation Failed', {
          code: 'invalid_param',
          errors,
        });
      }
    };

    data = data || this.request.body;
    if (Array.isArray(data)) {
      data.forEach(item => {
        toValidate(rules, item);
      });
    } else {
      toValidate(rules, data);
    }
  },
};
